package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"pet/cache"
	"pet/model"
	"time"

	"pet/petrpc/internal/svc"
	"pet/petrpc/petrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListPetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListPetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListPetLogic {
	return &ListPetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListPetLogic) ListPet(in *petrpc.ListPetRequest) (*petrpc.ListPetResponse, error) {
	// todo: add your logic here and delete this line
	var Pet []model.PetData
	result, _ := cache.Rdb.Get(cache.Ctx, "petlist").Result()
	if result == "" {
		err := model.DB.Model(&model.Pet{}).
			Select("pets.*,  classes.`name` AS class_name,  users.`name` AS user_name").
			Joins("  LEFT JOIN classes ON classes.id = pets.class_id").
			Joins("LEFT JOIN users ON classes.id = pets.user_id").
			Debug().Find(&Pet).Error
		if err != nil {
			return nil, errors.New("宠物领养信息查询失败")
		}
		marshal, _ := json.Marshal(Pet)
		cache.Rdb.Set(cache.Ctx, "petlist", marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &Pet)
	}
	var penData []*petrpc.ListPet
	for _, data := range Pet {
		fmt.Println(data)
		pet := petrpc.ListPet{
			Name:      data.Name,
			Gender:    data.Gender,
			Info:      data.Info,
			ClassName: data.ClassName,
			UserName:  data.UserName,
			PetId:     int64(data.ID),
		}
		penData = append(penData, &pet)
	}
	return &petrpc.ListPetResponse{
		List: penData,
	}, nil
}
